package com.hyh.ad.common.core.redis;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class CacheClient {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 存放不含过期时间的key
     *
     * @param key
     */
    public void setWithoutTime(String key, Object value) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value));
    }

    /**
     * redis的set方法是一个字符串的存储方法
     *
     * @param key:redis当中的唯一key，value:存储的值 类型为Object，time:过期时间，unit:时间单位
     */
    public void setObject(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }


    /**
     * 获取key
     *
     * @param key
     */
    public String getObject(String key) {
        if (key == null) {
            throw new RuntimeException("key不能为空");
        }
        return stringRedisTemplate.opsForValue().get(key);
    }

    /**
     * 获取key并转换为指定对象类型
     *
     * @param key   redis当中的唯一key
     * @param clazz 指定对象的类型
     * @param <T>   对象类型
     * @return 指定类型的对象
     */
    public <T> T getObject(String key, Class<T> clazz) {
        String json = getObject(key);
        if (json == null) {
            return null;
        }
        return jsonToObject(json, clazz);
    }



    private <T> T jsonToObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            throw new RuntimeException("JSON字符串转换为对象失败", e);
        }
    }


    /**
     * 删除key
     *
     * @param key
     */
    public void delete(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 用map的形式存储数据 加上过期时间
     *
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void setMap(String key, Object value, Long time, TimeUnit unit) {
        // 将对象转换为map
        Map<String, Object> map = BeanUtil.beanToMap(value, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> {
                    if (fieldValue == null)
                        return null;
                    return fieldValue.toString();
                }));

        // 存储map
        stringRedisTemplate.opsForHash().putAll(key, map);
        // 设置过期时间
        stringRedisTemplate.expire(key, time, unit);
    }

    /**
     * 用map的形式存储数据
     *
     * @param
     * @return
     */
    public void setMapWithoutTime(String key, Object value) {
        // 将对象转换为map
        Map<String, Object> map = BeanUtil.beanToMap(value, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> {
                    if (fieldValue == null)
                        return null;
                    return fieldValue.toString();
                }));

        // 存储map
        stringRedisTemplate.opsForHash().putAll(key, map);
    }

    /**
     * 获取map的数据
     *
     * @param key
     * @param bean
     */
    public <T> T getMap(String key, T bean) {
        if (key == null) {
            throw new RuntimeException("key不能为空");
        }
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
        // 将map转为bean
        return BeanUtil.fillBeanWithMap(entries, bean, false);
    }

    /**
     * 将list存储到redis当中 并且设置过期时间
     *
     * @param key
     * @param list
     * @param time
     * @param unit
     */
    public void setList(String key, List<?> list, Long time, TimeUnit unit) {
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        for (Object o : list) {
            try {
                opsForList.rightPush(key, objectMapper.writeValueAsString(o));
            } catch (JsonProcessingException e) {
                throw new RuntimeException("对象转换为JSON字符串失败", e);
            }
        }
        stringRedisTemplate.expire(key, time, unit);
    }

    /**
     * 将list存储到redis当中
     *
     * @param key
     * @param list
     */
    public void setListWithoutTime(String key, List<?> list) {
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        for (Object o : list) {
            opsForList.rightPush(key, JSONUtil.toJsonStr(o));
        }
    }

    /**
     * 获取list
     *
     * @param key   redis当中的唯一key
     * @param clazz 指定对象的类型
     * @param <T>   对象类型
     * @return 指定类型的对象列表
     */
    public <T> List<T> getList(String key, Class<T> clazz) {
        if (key == null) {
            throw new IllegalArgumentException("key不能为空");
        }
        ListOperations<String, String> opsForList = stringRedisTemplate.opsForList();
        List<String> range = opsForList.range(key, 0, -1);
        if (range == null || range.isEmpty()) {
            return new ArrayList<>();
        }
        List<T> resultList = new ArrayList<>();
        for (String json : range) {
            try {
                T object = objectMapper.readValue(json, clazz);
                resultList.add(object);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("JSON字符串转换为对象失败。JSON内容：" + json, e);
            }
        }
        return resultList;
    }



    /**
     * 将对象存入到redis set集合中 并且设置过期时间
     *
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void setSetWithoutTime(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForSet().add(key, JSONUtil.toJsonStr(value));
        stringRedisTemplate.expire(key, time, unit);
    }
    /**
     * 将对象存入到redis set集合中
     *
     * @param key
     * @param value
     */
    public void setSet(String key, Object value) {
        stringRedisTemplate.opsForSet().add(key, JSONUtil.toJsonStr(value));
    }
    /**
     * 获取set集合
     *
     * @param key
     * @param clazz
     * @return
     */
    public <T> List<T> getSet(String key, Class<T> clazz) {
        if (key == null) {
            throw new RuntimeException("key不能为空");
        }
        return BeanUtil.copyToList(stringRedisTemplate.opsForSet().members(key), clazz);
    }
}
